<template>
  <div id="mobile" @dblclick="screen">
    <div class="bg">
      <dv-loading v-if="loading">Loading...</dv-loading>
      <div v-else class="host-body">
        <!-- 头部 -->
        <pheader @changeCom="showComModal = true"></pheader>
        <div v-if="showComModal" class="all-model">
          <div class="model-view-box">
            <dv-border-box-11 title="选择系统" style="width: 800px;">
              <div class="c-box">
                <div v-for="item in poromissList" :key="item.id" class="item"
                  :class="item.id === companyLabFlag ? 'active' : ''" @click="checkCompnay(item.id)">
                  {{ item.name }}
                </div>
              </div>
            </dv-border-box-11>
          </div>
        </div>
        <div v-else class="body-box">
          <Tabs swipeable duration="0" @click="changeFun">
            <Tab title="地图">
              <div v-if="active === 0" class="body-first">
                <div class="body-center">
                  <div class="data-box">
                    <MapData :companyLabFlag="companyLabFlag"></MapData>
                  </div>
                </div>
              </div>
            </Tab>
            <Tab title="数据范围">
              <div v-if="active === 1" class="body-last">
                <div class="box-cell">
                  <Select :options="YeardataList" v-model="oneData" @change="timeChecked(false)" />
                  <div class="detail-b">
                    <div class="detail" @click="timeChecked(true)">详情表格</div>
                  </div>
                </div>
                <div class="box-cont">
                  <scope :TestMainId="oneData" :LabFlag="companyLabFlag" :LabName="LabName" :LabId="LabId"
                    :LabType="LabType"></scope>
                </div>
              </div>
            </Tab>
            <Tab title="可疑数据">
              <div v-if="active === 2" class="body-last">
                <div class="box-cell">
                  <div>&nbsp;</div>
                  <div class="detail-b">
                    <div class="detail" @click="timeCheckedThere(null)">详情表格</div>
                  </div>
                </div>
                <div class="com-cont">
                  <suspicious v-if="allData.SuspiciousData" :SuspiciousData="allData.SuspiciousData"></suspicious>
                </div>
              </div>
            </Tab>
            <Tab title="所选实验室数据分析">
              <div v-if="active === 3" class="body-last">
                <div class="box-cell">
                  <Select :disabled="disabled" :options="compnayList" v-model="moreParams.LabId" @change="timeFun" />
                  <vxe-select v-model="timeList" placeholder="多选" clearable multiple @change="timeFun"
                    style="width:120px">
                    <vxe-option v-for="time in YeardataList" :key="time.value" :value="time.value"
                      :label="time.label"></vxe-option>
                  </vxe-select>
                </div>
                <div class="com-cont">
                  <analyse v-if="allData.SuspiciousAndOutlierData"
                    :SuspiciousAndOutlierData="allData.SuspiciousAndOutlierData">
                  </analyse>
                </div>
              </div>
            </Tab>
            <Tab title="问题数据占比">
              <div v-if="active === 4" class="body-last">
                <div class="box-cell">
                  <Select :disabled="disabled" :options="compnayList" v-model="moreParams.LabId" @change="timeFun" />
                  <vxe-select v-model="timeList" placeholder="多选" clearable multiple @change="timeFun"
                    style="width:120px">
                    <vxe-option v-for="time in YeardataList" :key="time.value" :value="time.value"
                      :label="time.label"></vxe-option>
                  </vxe-select>
                </div>
                <div class="com-cont">
                  <problem v-if="allData.ProblemData" :ProblemData="allData.ProblemData"></problem>
                </div>
              </div>
            </Tab>
            <Tab title="离群数据">
              <div v-if="active === 5" class="body-last">
                <div class="com-cont">
                  <withdrawn v-if="allData.OutlierData" :OutlierData="allData.OutlierData"></withdrawn>
                </div>
              </div>
            </Tab>
            <Tab title="可疑数据/离群数据（占比）">
              <div v-if="active === 6" class="body-last">
                <div class="box-cell">
                  <div>&nbsp;</div>
                  <div class="detail-b">
                    <div class="detail" @click="timeCheckedTwo(null)">详情表格</div>
                  </div>
                </div>
                <div class="com-cont">
                  <withorsus v-if="allData.SuspiciousOutlierData"
                    :SuspiciousOutlierData="allData.SuspiciousOutlierData"> </withorsus>
                </div>
              </div>
            </Tab>
            <Tab title="结果优秀占比">
              <div v-if="active === 7" class="body-last">
                <div class="com-cont">
                  <result :TestMainId="resultData" :companyLabFlag="companyLabFlag"></result>
                </div>
              </div>
            </Tab>
            <Tab title="实验室历年数据变化趋势">
              <div v-if="active === 8" class="body-last">
                <div class="box-cell">
                  <Select :disabled="disabled" :options="compnayList" v-model="moreParams.LabId" @change="timeFun" />
                  <vxe-select v-model="timeList" placeholder="多选" clearable multiple @change="timeFun"
                    style="width:120px">
                    <vxe-option v-for="time in YeardataList" :key="time.value" :value="time.value"
                      :label="time.label"></vxe-option>
                  </vxe-select>
                </div>
                <div class="com-cont">
                  <trend v-if="allData.ItemDataResult" :ItemDataResult="allData.ItemDataResult"></trend>
                </div>
              </div>
            </Tab>
          </Tabs>
        </div>
      </div>
    </div>
    <Popup v-model:show="shoModel" position="right" class="popupWin" :style="{ width: '100vw', height: '100vh' }">
      <div class="popupWin">
        <div v-if="modelName === 'one'" class="model one">
          <NavBar title="参与实验室间的统计再现性与推荐试验方法的" left-arrow @click-left="closeModel" />
          <Jointable :datas="allData.ReproducibilityData"></Jointable>
        </div>
        <div v-else-if="modelName === 'two'" class="model">
          <NavBar title="数据总体情况表" left-arrow @click-left="closeModel" />
          <TwoTable :datas="allData.ReproducibilityData" :dataList="YeardataList" @timeCheckedTwo="timeCheckedTwo"
            :time="twoData"></TwoTable>
        </div>
        <div v-else-if="modelName === 'there'" class="model there">
          <NavBar title="实验室对应可疑结果情况表" left-arrow @click-left="closeModel" />
          <ThereTable :datas="allData.ReproducibilityData" :dataList="YeardataList" @timeCheckedTwo="timeCheckedThere"
            :time="thereData"></ThereTable>
        </div>
      </div>
    </Popup>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, computed } from "vue"
import useDraw from "@/utils/useDraw"
import pheader from "@/components/pheader/pheaderM.vue"
import MapData from "../map/MapData.vue"
import suspicious from '../suspicious/suspicious.vue'
import withdrawn from '../withdrawn/withdrawn.vue'
import withorsus from '../withorsus/withorsus.vue'
import analyse from '../analyse/analyse.vue'
import problem from '../problem/problem.vue'
import trend from '../trend/trend.vue'
import result from '../result/result.vue'
import scope from '../scope/scope.vue'
import API from '@/common/api'
import Jointable from '@/components/mTable/Jointable.vue'
import TwoTable from '@/components/mTable/TwoTable.vue'
import ThereTable from '@/components/mTable/ThereTable.vue'
import Select from '@/components/Select.vue'
import screenfull from 'screenfull'
import { Popup, Tab, Tabs, NavBar } from 'vant';
import { useRouter } from "vue-router";

const router = useRouter()
const allData = reactive({
  SuspiciousData: null,//可疑数据
  OutlierData: null,//离群数据
  SuspiciousOutlierData: null,//离群数据/可疑数据占比
  ItemDataResult: null,
  ProblemDataTotalCount: 0,
  SuspiciousAndOutlierData: null,
  ProblemData: null,
  ReproducibilityData: []
})
const active = ref(0)
const LabName = ref('')
const LabId = ref('')
const oneData = ref('')
const twoData = ref('')
const thereData = ref('')
const resultData = ref('')
const timeList = ref([])
const YeardataList = ref([])
const compnayList = ref([])
const companyLabFlag = ref(-1)
const poromissList = ref([])
const showComModal = ref(false)
const LabType = ref('')
const moreParams = ref(
  {
    "TestMainIdList": [
      {
        "TestMainId": "",//年份对应的ID
        "TestYear": '' //年份
      }
    ],
    //登录返回的LabInfo 数据，页面是可以选择哪个化验室的
    "LCode": "", //实验室代码
    "LabId": "" //实验室ID 
  }
)
const screen = () => {
  screenfull.toggle()
  // ElMessage('全屏啦')
}
// * 加载标识
const loading = ref<boolean>(true)
const shoModel = ref(false)
const modelName = ref('')
// * 适配处理
const { appRef, calcRate, windowDraw, unWindowDraw } = useDraw()
const disabled = computed(() => {
  const iindex = compnayList.value.findIndex(e => e.value === LabId.value)
  return companyLabFlag.value === 0 || iindex < 0
})
// 生命周期
onMounted(() => {
  const data = localStorage.getItem('info')
  if (data) {
    const datatem = JSON.parse(data)
    YeardataList.value = datatem.Yeardata.map((e) => {
      const item = {
        label: e.TestYear,
        value: e.TestMainId
      }
      return item
    })

    compnayList.value = datatem.LabInfo.map((e) => {
      const item = {
        label: e.ShortName,
        value: e.Id,
        code: e.LCode
      }
      return item
    })
    timeList.value = YeardataList.value.map((e) => e.value)
    oneData.value = YeardataList.value[0].value
    twoData.value = YeardataList.value[0].value
    resultData.value = YeardataList.value[0].value
    thereData.value = YeardataList.value[0].value
    LabType.value = datatem.LabType
    LabName.value = datatem.ShortName
    LabId.value = datatem.Id
    if (datatem.LabFlag === 0) {
      poromissList.value = [{ id: 0, name: '本公司' }]
    } else if (datatem.LabFlag === 1) {
      poromissList.value = [{ id: 0, name: '本公司' }, { id: 1, name: '总公司' }]
    } else if (datatem.LabFlag === 2) {
      poromissList.value = [{ id: 0, name: '本公司' }, { id: 2, name: '地区公司' }]
    } else {
      poromissList.value = [{ id: 0, name: '本公司' }, { id: 1, name: '总公司' }, { id: 2, name: '地区公司' }]
    }
    poromissList.value.push({ id: 999, name: '退出登录' })
    moreParams.value = {
      "TestMainIdList": [
        {
          "TestMainId": YeardataList.value[0].value,//年份对应的ID
          "TestYear": YeardataList.value[0].label //年份
        }
      ],
      //登录返回的LabInfo 数据，页面是可以选择哪个化验室的
      "LCode": datatem.LCode, //实验室代码
      "LabId": datatem.Id //实验室ID 
    }
    const flag = sessionStorage.getItem('companyLabFlag')
    if (datatem.LabFlag !== 0 && flag === null) {
      showComModal.value = true
    } else {
      companyLabFlag.value = Number(flag)
      GetSuspiciousDataChartFun()
      GetLabDataChart()
    }
  }
  cancelLoading()
})


// methods
const GetSuspiciousDataChartFun = async () => {
  allData.SuspiciousOutlierData = null
  allData.OutlierData = null
  allData.SuspiciousData = null
  const data = localStorage.getItem('info')
  if (data) {
    const loaclData = JSON.parse(data)
    let Yeardata = loaclData.Yeardata
    let LocalYeardata = loaclData.LocalYeardata
    let res: any = null

    if (companyLabFlag.value === 1) {
      res = await API.GetSuspiciousDataChart({ Yeardata })
    } else {
      const params = {
        "Yeardata": companyLabFlag.value === 0 ? LocalYeardata : Yeardata,
        "LabFlag": companyLabFlag.value,  //传0 表示本化验室  2 表示地区公司    
        "LabType": loaclData.LabType,//登录返回的化验类型
        "LabId": loaclData.Id,//登录返回的化验室的ID
        "LabName": loaclData.ShortName// 登录返回的化验室的名称
      }
      res = await API.GetLocalSuspiciousDataChart(params)
    }

    if (res.Tag) {
      allData.SuspiciousOutlierData = res.Data.SuspiciousOutlierData
      allData.OutlierData = res.Data.OutlierData
      allData.SuspiciousData = res.Data.SuspiciousData
    }
  }
}
const checkCompnay = (id) => {
  if (id === 999) {
    localStorage.clear()
    sessionStorage.clear()
    router.replace('/ml')
  } else {
    showComModal.value = false
    companyLabFlag.value = id
    sessionStorage.setItem('companyLabFlag', id)
    GetSuspiciousDataChartFun()
    GetLabDataChart()
    active.value = 0
  }
}

// 根据实验室和年份筛选数据
const GetLabDataChart = async () => {
  allData.ProblemData = null //问题占比数据
  allData.SuspiciousAndOutlierData = null  // 可疑和离群数据次数
  allData.ItemDataResult = null  // 可年底数据变化趋势 数据
  moreParams.value.TestMainIdList = timeList.value.map((e) => {
    const data = YeardataList.value.find((f) => f.value === e)
    if (data) {
      return {
        "TestMainId": data.value,//年份对应的ID
        "TestYear": data.label //年份
      }
    }
  })

  const res: any = await API.GetLabDataChart(moreParams.value)
  if (res.Tag) {
    allData.ProblemDataTotalCount = res.Data.ProblemDataTotalCount //问题占比总数
    allData.ProblemData = res.Data.ProblemData //问题占比数据
    allData.SuspiciousAndOutlierData = res.Data.SuspiciousAndOutlierData // 可疑和离群数据次数
    allData.ItemDataResult = res.Data.ItemDataResult // 可年底数据变化趋势 数据
  }
}

// todo 处理 loading 展示
const cancelLoading = () => {
  setTimeout(() => {
    loading.value = false
  }, 500)
}

const timeChecked = (type) => {
  console.log('------');

  modelName.value = 'one'
  if (shoModel.value || type) {
    GetReproducibilityDataFun()
  }
}

const closeModel = () => {
  shoModel.value = false
  modelName.value = ''
}

const timeCheckedThere = (value) => {
  modelName.value = 'there'
  if (value) {
    thereData.value = value
  }
  GetReproducibilityDataFun()
}

const timeFun = () => {
  const LCode = compnayList.value.find(e => e.value === moreParams.value.LabId)
  moreParams.value.LCode = LCode.code
  GetLabDataChart()
}

const timeCheckedTwo = (value) => {
  modelName.value = 'two'
  if (value) {
    twoData.value = value
  }
  GetReproducibilityDataFun()

}
const GetReproducibilityDataFun = async () => {
  if (modelName.value === 'one') {
    const res: any = await API.GetReproducibilityData({ "TestMainId": oneData.value })
    if (res.Tag) {
      shoModel.value = true
      allData.ReproducibilityData = res.Data.ReproducibilityData
    }
  } else if (modelName.value === 'two') {
    const res: any = await API.GetOverallData({ "TestMainId": twoData.value })
    if (res.Tag) {
      shoModel.value = true
      allData.ReproducibilityData = res.Data
    }
  } else if (modelName.value === 'there') {
    const res: any = await API.GetSuspiciousData({ "TestMainId": thereData.value })
    if (res.Tag) {
      shoModel.value = true
      allData.ReproducibilityData = res.Data
    }
  }
}

const changeFun = (index) => {
  console.log('index', index);

  active.value = index
}

</script>

<style lang="scss" scoped>
@import "@/assets/mobile/index.scss";

.flex {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.detail-b {
  position: relative;
  width: 100px;

  .detail {
    top: -18px;
    right: 0;
    position: absolute;
    cursor: pointer;
    border: 1px solid #ffffff92;
    background-color: #1C5BEC;
    font-size: 14px;
    height: 32px;
    display: flex;
    align-items: center;
    padding: 0px 6px;
  }
}

.dropdown:hover .dropdown-content {
  display: block;
}

.z100 {
  position: relative;
  z-index: 1001;
}

.model-view {
  position: fixed;
  left: 0;
  top: 0;
  right: 0;
  bottom: 0;
  z-index: 1000;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(0, 0, 0, 0.75);

  .model {
    &.one {
      margin-left: 100px;
      width: 1000px;
    }

    &.there {
      margin-left: 450px;
      width: 1400px;
    }

    margin-left: 900px;
    position: absolute;
    width: 900px;
    max-height: 90vh;
    min-height: 50vh;
    background: url('../../assets/images/model.png');
    background-size: 100% 100%;
    padding: 30px 30px 40px;

    .close {
      position: absolute;
      right: 30px;
      font-size: 24px;
      cursor: pointer;
    }
  }
}

::v-deep(.vxe-input--inner) {
  color: #ffffff;
  background-color: #0A4FE8;
}

::v-deep(.vxe-select--panel-wrapper) {
  background-color: #0A4FE8;
  color: #ffffff;
}

::v-deep(.vxe-select-option) {
  &.is--hover {
    background-color: #25435f;
    color: #ffffff;
  }

  &.is--selected {
    background-color: #5aa2e0;
    color: #ffffff;
  }
}

.popupWin {
  height: 100vh;
  width: 100w;
  background-image: url("../../assets/pageBg.jpg");
  background-size: cover;
  background-position: center center;
  position: fixed
}

.all-model {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  top: 0;
  z-index: 1000;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: rgba(0, 0, 0, 0.75);

  .model-view-box {
    width: 80vw;
    height: 42vh;
    display: flex;
    align-items: center;
    justify-content: center;

    .c-box {
      margin-top: 30px;
      width: 80vw;
      height: 42vh;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;

      .item {
        &:hover {
          font-size: 1.2rem;
          color: #2a64f5;
        }

        &.active {
          background: #416fe3;
          font-size: 1.2rem;
          color: #ffffff !important;
        }

        transition: all 0.3s;
        cursor: pointer;
        width: 80%;
        height: 3.5rem;
        border: 1px solid rgb(138, 170, 251);
        margin-bottom: 1rem;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 1.2rem;
        font-weight: bold;
      }
    }

  }

}
</style>

<style>
.van-tabs__nav {
  background: none
}

.van-tab {
  color: #ffffff;
}
</style>
